import { useRequest } from '@umijs/hooks';
import { FileExcelOutlined} from '@ant-design/icons'
import {
    Button, Card,Tabs,Select,
    Form,
    Input,
    Layout,
    Menu,
    message,
    Popconfirm,
    Radio,
    Table,
    Tag,
    Tree,
    TreeSelect,
    Upload
} from 'antd';
import { Store } from 'rc-field-form/lib/interface';
import React, {useState} from 'react';
import {useDispatch, useSelector} from 'react-redux';
import {getOriginString, getSecretString} from '../../../../utils/encrypt';
import { fetchRequest } from '../../../../utils/Request';
import { url } from '../../../../utils/url';
import XLSX from 'xlsx';
import TableSetting from "../../../../components/TableSetting/TableSetting";
import actionType from "./addressActionType";


export default function AddAddress(props: any) {

    const { TabPane } = Tabs;
    const [currentKey,setCurrentKey] = useState('1');
    const [excelTableData,setExcelTableData] = useState<any[]>([]);
    const [batchAddDeptId, setBatchAddDeptId] = useState<any>('');
    const [batchAddList, setBatchAddList] = useState<any[]>([]);
    const [excelFlag,setExcelFlag] = useState<boolean>(false);
    const  errorcolumns=[{title: "错误说明", dataIndex: 'errorTitle', key: 'errorTitle'}]

    const columns = [
        {title: "楼栋", dataIndex: 'building', key: 'building',render:(text:string)=>{
                if(text === ""){
                    return <Tag color={'#f50206'}>楼栋未填</Tag>;
                }
                if(!/^[0-9]\d*$/.test(text)){
                    return <Tag color={'#f50206'}>{text}:格式异常</Tag>;
                }
                return text;
            }
        },
        {title: "单元", dataIndex: 'unit', key: 'unit',render:(text:string)=>{
                if(text === ""){
                    return <Tag color={'#f50206'}>单元未填</Tag>;
                }
                if(!/^[0-9]\d*$/.test(text)){
                    return <Tag color={'#f50206'}>{text}:格式异常</Tag>;
                }
                return text;
            }
        },
        {title: "层", dataIndex: 'floor', key: 'floor',render:(text:string)=>{
                if(text === ""){
                    return <Tag color={'#f50206'}>楼层未填</Tag>;
                }
                if(!/^[0-9]\d*$/.test(text)){
                    return <Tag color={'#f50206'}>{text}:格式异常</Tag>;
                }
                return text;
            }
        },
        {title: "房号", dataIndex: 'room', key: 'room',render:(text:string)=>{
                if(text === ""){
                    return <Tag color={'#f50206'}>房间号未填</Tag>;
                }
                if(!/^[0-9]\d*$/.test(text)){
                    return <Tag color={'#f50206'}>{text}:格式异常</Tag>;
                }
                return text;
            }
        }
    ];


    //获取redux中的数据
    const myData = useSelector((state: any) => {
        const data = state.addressManage.campusselect
        disableSelect(data)
        return {
            campusData: data,
        }
    });

    //获取redux中的数据
    const errorTableData = useSelector((state: any) => {
        return state.addressManage.errorTableData

    });
    console.log(errorTableData)
    // console.log(myData.campusData)
    function handleExcelFile(e:any) {
        if(e.target.files[0]===null||e.target.files[0]===undefined){
            return false;
        }
        let f = e.target.files[0];
        let reader = new FileReader();  // 使用 FileReader 读取数据
        reader.onload = function(e) {  // 数据读取完成后的回调函数
            try{
                // @ts-ignore
                let workbook = XLSX.read(e.target.result, {type: 'binary'})
                let firstSheetName = workbook.SheetNames[0];  // 获取第一个 sheet 的名字
                let worksheet = workbook.Sheets[firstSheetName];  // 获取第一个 sheet 的内容
                let res = XLSX.utils.sheet_to_json(worksheet);  // 使用 utils 里的方法转换内容为便于使用的数组
                console.log(res)
                const list:any[]=[];
                const addList:any[]=[];
                res.map((item:any) => {
                    console.log(item.证件号码)
                    list.push({
                        rowNum:item.__rowNum__,
                        building: (item.楼栋===""|| item.楼栋===undefined)?"":item.楼栋.trim(),
                        unit:  (item.单元===""|| item.单元===undefined)?"":item.单元.trim(),
                        floor:  (item.楼层===""|| item.楼层===undefined)?"":item.楼层.trim(),
                        room: (item.房间号===""|| item.房间号===undefined)?"":item.房间号.trim()
                    })
                    addList.push({
                        building: (item.楼栋===""|| item.楼栋===undefined)?"":item.楼栋.trim(),
                        unit:  (item.单元===""|| item.单元===undefined)?"":item.单元.trim(),
                        floor:  (item.楼层===""|| item.楼层===undefined)?"":item.楼层.trim(),
                        room: (item.房间号===""|| item.房间号===undefined)?"":item.房间号.trim().toString()
                    })
                });
                console.log("读取list")
                console.log(addList)
                setExcelTableData(list);
                excelDataCheck(addList);
            }
            catch (e) {
                message.error("数据异常！");
            }
        };
        reader.readAsBinaryString(f);  // 读取数据
    }

    function excelDataCheck(data:any) {
        let falseFlag = true;
        let repeaterror="";
        for(let i = 0;i<data.length;i++){
            if(data[i].building===""||data[i].unit===""||data[i].floor===""||data[i].room===""){
                falseFlag=false;
            }
            else if(!/^[0-9]\d*$/.test(data[i].unit)){
                falseFlag=false;
            }
            else if(!/^[0-9]\d*$/.test(data[i].building)){
                falseFlag=false;
            }
            else if(!/^[0-9]\d*$/.test(data[i].floor)){
                falseFlag=false;
            }
            else if(!/^[0-9]\d*$/.test(data[i].room)){
                falseFlag=false;
            }
            let temp = data[i];
            for (let j = i + 1; j < data.length; j++)
            {
                if (temp.unit===data[j].unit&&temp.building===data[j].building&&temp.floor===data[j].floor&&temp.room===data[j].room)
                {
                    repeaterror= temp.building + "栋"+temp.unit+"单元"+temp.room+"房间号有多条数据";
                    falseFlag=false;
                }
            }


        }
        
        if(falseFlag){

            setBatchAddList(data);
            setExcelFlag(true);
        }
        else {
            message.error(repeaterror);
            setExcelFlag(false);
        }
    }


    //递归修改item的key
    function disableSelect(arr: any[], ) {
        arr.map(item => {
            delete item.disabled
            item.value = item.collegeId+"-"+item.collegeAreaId
            item.title = item.collegeAndArea
            if (typeof item.children === "undefined" || item.children === null || item.children.length === 0) {
                return;
            } else {
                disableSelect(item.children)
            }
        })
    }
    //递归修改item的key
    function disableError(arr: any[], ) {
        arr.map(item => {
            delete item.disabled
            item.value = item.collegeId+"-"+item.collegeAreaId
            item.title = item.collegeAndArea
            if (typeof item.children === "undefined" || item.children === null || item.children.length === 0) {
                return;
            } else {
                disableSelect(item.children)
            }
        })
    }


    // const treeData1=disableSelect(treeData)
    const [form] = Form.useForm();
    const dispatch = useDispatch()
    const layout = {
        labelCol: { span: 5 },
        wrapperCol: { span: 14 },
    };

    const tailLayout = {
        wrapperCol: { offset: 5, span: 14 },
    };


    function onFinish(value: Store) {
        console.log(value)
        const data = {
            building: value.building,
            unit: value.unit,
            floor:value.floor,
            room:value.room};
        const params = {
            collegeId:value.deptId.split('-')[0],
            collegeAreaId:value.deptId.split('-')[1],
            listAddress: [data]
        };
        addNewAddressOne.run(params)

    }

    function menuClick(e:any){
        setCurrentKey(e.key);
    }

    function batchTreeOnchange(value:any){
        setBatchAddDeptId(value)
    }

    function batchAddClick(){
        if(batchAddDeptId===""){
            message.error("请选择校区！");
            return;
        }
        if(!excelFlag){
            message.error("excel数据异常，请修改！");
            return;
        }

        const param = {
            collegeId:batchAddDeptId.split('-')[0],
            collegeAreaId:batchAddDeptId.split('-')[1],
            listAddress:batchAddList
        };
        // console.log(param)
        addNewAddress.run(param);
    }

    async function addNewAddressRequest(params: any)
    {
        console.log(params)
        try {
            const json = await fetchRequest(url.ADD_ADDRESS_INFORMATION, params);
            console.log(json)
            if (json.success&&json.info.falseCount===0) {
                message.destroy();
                message.success("新增成功!");
                props.addSuccess();
            } else {
                if(json.info.falseCount!=0)
                {
                    message.destroy();
                    message.error("部分导入成功，导入成功"+json.info.successCount+"条，失败"+json.info.falseCount+"条！详情请看错误提示！！！");
                    dispatch({ type: actionType.GET_ERROR_LIST,
                        payload:{data: json.info.errorList,count:json.info.falseCount
                    }})
                }
                else
                {
                    dispatch({ type: actionType.GET_ERROR_LIST,
                        payload:{data: json.info.errorList,count:json.info.falseCount
                        }})
                    message.destroy();
                    message.error(json.info.error+"，详情请看错误提示！！！");

                }

            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message);
        }
    }

    async function addNewAddressOneRequest(params: any)
    {
        console.log("单个新增")
        try {
            const json = await fetchRequest(url.ADD_ADDRESS_INFORMATION, params);
            console.log(json)
            if (json.success) {
                message.destroy();
                message.success("新增成功!");
                props.addSuccess();
            } else {
                    message.destroy();
                    message.error("新增失败！"+json.info.errorList[0].errorTitle);
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message);
        }
    }

    const addNewAddress = useRequest(addNewAddressRequest, {
        manual: true,
        loadingDelay: 200
    })

    const addNewAddressOne = useRequest(addNewAddressOneRequest, {
        manual: true,
        loadingDelay: 200
    })

    return (
        <div>
            <Tabs >
                <TabPane tab="标准地址单个新增" key="2">
                    <div  className="site-layout-background" style={{ minHeight: 380 }}>
                        <Form form={form} {...layout} onFinish={onFinish} >
                            <Form.Item className="form-control-item" name="deptId" label="校区" rules={[{ required: true, message: '必须要选择组织机构' }]}>
                                <TreeSelect className="search-form-item"
                                            treeData={myData.campusData}
                                    //         treeData={treeData}
                                            treeDefaultExpandAll placeholder="请选择校区"/>
                            </Form.Item>
                            <Form.Item label="楼栋" name="building" rules={[{ required: true, message: '必须输入楼栋' },{ pattern:/^[0-9]\d*$/, message: '楼栋只能输入数字！' }]}>
                                <Input placeholder="请输入楼栋"/>
                            </Form.Item>

                            <Form.Item label="单元" name="unit" rules={[{ required: true, message: '必须输入单元' },{ pattern:/^[0-9]\d*$/, message: '单元只能输入数字！' }]}>
                                <Input placeholder="请输入单元"/>
                            </Form.Item>
                            <Form.Item label="层" name="floor" rules={[{ required: true, message: '必须输入层' },{ pattern:/^[0-9]\d*$/, message: '单元只能输入数字！' }]}>
                                <Input placeholder="请输入层"/>
                            </Form.Item>
                            <Form.Item label="房号" name="room" rules={[{ required: true, message: '必须输入房号' },{ pattern:/^[0-9]\d*$/, message: '房号只能输入数字！' }]}>
                                <Input placeholder="请输入房号"/>
                            </Form.Item>
                            <Form.Item {...tailLayout}>
                                <Button type="primary" htmlType="submit" loading={addNewAddress.loading}>提交</Button>
                            </Form.Item>
                        </Form>
                    </div>
                </TabPane>
                <TabPane tab="标准地址批量新增" key="3">
                    <div className="site-layout-background" style={{  minHeight: 380 }}>
                        <div style={{ display:"flex",flexDirection:"row",alignItems:"center",padding:20}}>
                            <span>导入模板：</span>
                            <a href={require('../../../../excel/标准地址批量导入模板.xlsx')} download>模板下载</a>
                        </div>
                        <div style={{ display:"flex",flexDirection:"row",alignItems:"center",padding:20}}>
                            <span>校区：</span>
                            <TreeSelect className="search-form-item"
                                        treeData={myData.campusData}
                                        onChange={batchTreeOnchange}
                                //         treeData={treeData}
                                        treeDefaultExpandAll />
                            {/*<Select id="batch-tree" className="search-form-item"*/}
                                    {/*showSearch*/}
                                    {/*// onChange={batchTreeOnchange}*/}
                            {/*>*/}
                                {/*/!*{data}*!/*/}
                            {/*</Select>*/}
                        </div>
                        <div style={{ display:"flex",flexDirection:"row",alignItems:"center",padding:20}}>
                            <span>上传文件：</span>
                            <input type="file" accept=".xlsx,.xls" onChange={handleExcelFile}/>
                        </div>
                        <div style={{ padding:20 }}>
                            <span>数据预览：</span>
                            <Table style={{ marginTop:20 }}
                                   pagination={{ hideOnSinglePage: true, simple: true,pageSize:10,total: excelTableData.length  }}
                                   rowKey={(record: any) => record.rowNum} columns={columns} dataSource={excelTableData} />
                        </div>
                        <div  style={{ padding:20 }}>
                            <Button type="primary" htmlType="submit" onClick={batchAddClick} loading={addNewAddress.loading}>提交</Button>
                        </div>
                        <div style={{ padding:20 }}>
                            <span>错误提示：</span>
                            <Table style={{ marginTop:20 }}
                                   pagination={{ hideOnSinglePage: true, simple: true,pageSize:10,
                                       total: excelTableData.length  }}
                                   rowKey={(record: any) => record.rowNum} columns={errorcolumns} dataSource={errorTableData.data} />
                        </div>
                    </div>
                </TabPane>
            </Tabs>
        </div>
    )

}
